<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>引出生命周期</title>
  </head>
  <body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>

    <!-- 引入react核心库 -->
    <script src="../js/react.development.js"></script>

    <!-- 引入react-dom用于支持react操作DOM  -->
    <script src="../js/react-dom.development.js"></script>

    <!-- 引用bable,用于将jsx转为js -->
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">
      // 创建组件
      class Life extends React.Component {
        state = {
          opacity: 0.1,
        }

        death = () => {
          // 卸载组件
          ReactDOM.unmountComponentAtNode(document.getElementById('test'))
        }

        // 组件挂载完毕就调用
        componentDidMount() {
          this.timer = setInterval(() => {
            // 获取原状态
            let { opacity } = this.state
            // 透明度减小0.1
            opacity -= 0.1
            if (opacity <= 0) opacity = 1
            // 设置新的透明度
            this.setState({ opacity: opacity })
          }, 200)
        }

        // 组件将要卸载时调用
        componentWillUnmount() {
          clearInterval(this.timer)
        }

        // 初始化渲染，状态更新之后。
        render() {
          return (
            <div>
              <h2 style={{ opacity: this.state.opacity }}>
                React学不会,怎么办?
              </h2>
              <button onClick={this.death}>不活了</button>
            </div>
          )
        }
      }

      // 渲染组件到页面
      ReactDOM.render(<Life />, document.getElementById('test'))
    </script>
  </body>
</html>
